package com.unswift.cloud.service.imports.system;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import com.unswift.cloud.adapter.logger.LoggerImportTaskAdapter;
import com.unswift.cloud.adapter.system.organization.SystemJobAdapter;
import com.unswift.cloud.adapter.validate.IValidateAdapter;
import com.unswift.cloud.enums.OperatorTypeEnum;
import com.unswift.cloud.enums.imports.task.ImportTaskEventEnum;
import com.unswift.cloud.imports.IImportBusinessService;
import com.unswift.cloud.pojo.bo.system.job.SystemJobImportBo;
import com.unswift.cloud.pojo.bo.system.job.SystemJobImportStopBo;
import com.unswift.cloud.pojo.dao.logger.imports.task.LoggerImportTaskInsertDo;
import com.unswift.cloud.pojo.dao.system.job.SystemJobInsertBatchDo;
import com.unswift.cloud.pojo.dao.system.job.SystemJobInsertBatchItemDo;
import com.unswift.cloud.pojo.mo.system.job.SystemJobImportMo;
import com.unswift.cloud.pojo.mso.logger.imports.task.LoggerImportTaskQueueMso;
import com.unswift.cloud.pojo.vo.system.job.SystemJobImportStopVo;
import com.unswift.cloud.pojo.vo.system.job.SystemJobImportVo;
import com.unswift.cloud.rabbit.RabbitConstant;
import com.unswift.cloud.rabbit.RabbitQueue;
import com.unswift.cloud.service.BaseService;
import com.unswift.cloud.service.LoggerService;
import com.unswift.utils.ExceptionUtils;
import com.unswift.utils.JsonUtils;

@Service
@Api(value="职位导入服务", author="liyunlong", date="2024-01-11", version="1.0.0")
public class SystemJobImportService extends BaseService implements IImportBusinessService<SystemJobImportMo, SystemJobImportBo>, RabbitConstant{
	
	@Autowired
	@ApiField("职位公共服务")
	private SystemJobAdapter systemJobAdapter;
	
	@Autowired
	@ApiField("导出任务服务")
	private LoggerImportTaskAdapter loggerImportTaskAdapter;
	
	@Autowired
	@ApiField("操作日志服务")
	private LoggerService loggerService;
	
	@Autowired
	@ApiField("Rabbit Mq发送消息服务")
	private RabbitQueue rabbitQueue;
	
	@Autowired
	@ApiField("表单验证公共操作")
	private IValidateAdapter validateAdapter;
	
	@ApiMethod(value="导入会员(不要加事务，否则有可能导致任务还没创建，但是队列已经消费查询，最终导致导入报错)", params=@ApiField("导入业务实体，包含附件信息"), returns=@ApiField("导入结果Vo->result:{0：未被导入，1：已成功导入}"))
	public SystemJobImportVo imports(SystemJobImportBo importBo) {
		ExceptionUtils.trueException(loggerImportTaskAdapter.existsTasking(this.getUserId(), systemJobAdapter.getModule()), "task.is.currently.executing", "有职位导入");
		Date date=new Date();
		LoggerImportTaskInsertDo task=new LoggerImportTaskInsertDo();
		task.setName("职位");
		task.setModule(systemJobAdapter.getModule());
		task.setDocumentType("excel");
		task.setStatus((byte)0);
		task.setStartTime(date);
		task.setImportBeanClass(this.getClass().getName());
		task.setImportModelClass(SystemJobImportBo.class.getName());
		task.setImportData(JsonUtils.toJson(importBo));
		task.setResult((byte)0);
		int result=loggerImportTaskAdapter.save(task, false);//保存任务，不用加事务，防止队列消费的时候还没保存完数据
		rabbitQueue.sendMessage(IMPORT_EXCHANGE_NAME, IMPORT_ROUTE_KEY, new LoggerImportTaskQueueMso(task.getId(), ImportTaskEventEnum.START, this.getHeader(tokenConfig.getKeyName()), getLanguage()));//发送导出队列
		return new SystemJobImportVo(task.getId(), result);
	}
	
	@ApiMethod(value="停止导出职位", params=@ApiField("停止导出对象"))
	public SystemJobImportStopVo stop(SystemJobImportStopBo importStopBo){
		rabbitQueue.sendMessage(IMPORT_STOP_EXCHANGE_NAME, IMPORT_STOP_ROUTE_KEY, new LoggerImportTaskQueueMso(importStopBo.getId(), ImportTaskEventEnum.STOP, this.getHeader(tokenConfig.getKeyName()), getLanguage()));//发送停止导出队列
		return new SystemJobImportStopVo(1);
	}
	
	@Override
	@ApiMethod(value="获取导出模板的类类型", returns=@ApiField("导出模板类类型"))
	public Class<SystemJobImportMo> getModule(){
		return SystemJobImportMo.class;
	}
	
	@Override
	@ApiMethod(value="导入行数据验证，请再此处处理完所有的验证，否则可能导致数据导入一部分", params = {@ApiField("需验证的行数据"), @ApiField("此数据在excel中的行次（从零开始）"), @ApiField("操作导出的用户token"), @ApiField("导入条件")})
	public void validate(SystemJobImportMo rowData, int rowIndex, String token, SystemJobImportBo condition) {
		rowData.setRowNumber(rowIndex+1);
		validateAdapter.validate(systemJobAdapter.getModule(), "import", rowData, this.getUser(token), systemJobAdapter);//验证表单
	}
	
	@Override
	@Transactional("systemTransactionManager")
	@ApiMethod(value="导入数据批量处理，批次数据根据nocos配置确定批次大小", params = {@ApiField("批次数据"), @ApiField("此列表在excel中的开始行次（从零开始）"), @ApiField("操作导出的用户token"), @ApiField("导入条件")})
	public void handleBatch(List<SystemJobImportMo> rowList, int startRowIndex, String token, SystemJobImportBo condition) {
		Long userId=this.getUserId(token);
		List<SystemJobInsertBatchItemDo> batchList=this.convertPojoList(rowList, SystemJobInsertBatchItemDo.class);
		int sort=systemJobAdapter.findMaxSort();
		for (SystemJobInsertBatchItemDo batchItem : batchList) {
			batchItem.setSort(sort);
			batchItem.setStatus((byte)1);
			batchItem.setCreateUser(userId);
			batchItem.setChangeUser(userId);
			sort++;
		}
		systemJobAdapter.saveBatch(new SystemJobInsertBatchDo(batchList), true);//批量插入数据
		int index=0;
		for (SystemJobImportMo importData : rowList) {
			long id=batchList.get(index).getId();
			loggerService.writer(id, systemJobAdapter.getModule(), OperatorTypeEnum.IMPORT, token, importData);//记录日志
			index++;
		}
	}
	
	@Override
	@ApiMethod(value="结束导入时触发，如清理临时缓存等", params = {@ApiField("用户token")})
	public void finish(String token) {
		validateAdapter.finish();
	}
}